package io.vov.vitamio.tvpaser;


import io.vov.vitamio.entity.TVProgram;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/** 从XML读取电视台节目 */
public class TVProgramReaderHelper {

	
	/**
	 * 获取电视节目单
	 * @param xml_content
	 * @return
	 */
	public static List<TVProgram> getTVProgramList(InputStream input) {
		List<TVProgram> result = new ArrayList<TVProgram>();
		DocumentBuilderFactory docBuilderFactory = null;
		DocumentBuilder docBuilder = null;
		Document doc = null;
		try {
			docBuilderFactory = DocumentBuilderFactory.newInstance();
			docBuilder = docBuilderFactory.newDocumentBuilder();
			doc = docBuilder.parse(input);
			Element root = doc.getDocumentElement();
			NodeList nodeList = root.getElementsByTagName("tvProgramTable");
			for (int i = 0; i < nodeList.getLength(); i++) {
				NodeList childList = nodeList.item(i).getChildNodes();// tvProgramTable
				if(childList == null || childList.getLength() >  0){
					TVProgram tvProgram = new TVProgram();
					for (int j = 0; j < childList.getLength(); j++) {
						Node childNode = childList.item(j);
						if("playTime".equals(childNode.getNodeName())){
							tvProgram.setPlayTime(childNode.getTextContent());
						}else if("meridiem".equals(childNode.getNodeName())){
//							tvProgram.setMeridiem(childNode.getTextContent());
						}else if("tvProgram".equals(childNode.getNodeName())){
							tvProgram.setTitle(childNode.getTextContent());
						}else if("tvStationInfo".equals(childNode.getNodeName())){
//							tvProgram.setTvStationInfo(childNode.getTextContent());
						} 
					}
					if(tvProgram.getPlayTime() != null){
						result.add(tvProgram);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} finally {
			doc = null;
			docBuilder = null;
			docBuilderFactory = null;
		}
		return result;
	}

}
